package com.mon4cc.simulation.logWriter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mon4cc.cmon.model.event.IEvent;
import com.mon4cc.simulation.ExecuteContext;
import com.mon4cc.simulation.FlowNodeSimulatedInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author Ping
 * @date 2022/12/20 0:49
 **/

public class Log4jWriter implements LogWriter {
    private ObjectMapper jsonMapper  ;
    private Logger log ;

    public Log4jWriter() {
        this.jsonMapper = new ObjectMapper();
        this.jsonMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
        this.log = LoggerFactory.getLogger(Log4jWriter.class) ;
    }


    private void write(Map<String, Object> params) {
        try {
            log.info(jsonMapper.writeValueAsString(params));
        } catch (Exception e) {
            System.err.print("[ERROR] " + e.getMessage());
        }
    }

    @Override
    public void write(FlowNodeSimulatedInstance currentInstance, ExecuteContext context) {

        Map<String, Object> map = context.currentDataContext() ;
        Assert.notNull(map, "Data Map should be not null.") ;
        map.put(IEvent.ATTR_NAME_FOR_CASE_ID, context.getCaseId()) ;
        map.put(IEvent.ATTR_NAME_FOR_ENAME, currentInstance.getName()) ;
        map.put(IEvent.ATTR_NAME_FOR_TIME, new Date()) ;
        write(map) ;
        context.increaseTotalNum();

    }

    @Override
    public void write(String eventName, ExecuteContext context) {
        Map<String, Object> map = context.currentDataContext() ;
        Assert.notNull(map, "Data Map should be not null.") ;
        map.put(IEvent.ATTR_NAME_FOR_CASE_ID, context.getCaseId()) ;
        map.put(IEvent.ATTR_NAME_FOR_ENAME, eventName) ;
        map.put(IEvent.ATTR_NAME_FOR_TIME, new Date()) ;
        write(map) ;
        context.increaseTotalNum();
    }

    @Override
    public void write(ExecuteContext context, FlowNodeSimulatedInstance currentInstance, Map<String, Object> map) {

        Assert.notNull(map, "Data Map should not be null.") ;
        Assert.notNull(context.getCaseId(), "CaseId should not be  null.") ;
        map.put(IEvent.ATTR_NAME_FOR_CASE_ID, context.getCaseId()) ;
        map.put(IEvent.ATTR_NAME_FOR_ENAME, currentInstance.getName()) ;
        map.put(IEvent.ATTR_NAME_FOR_TIME, new Date()) ;
        write(map) ;
        context.increaseTotalNum();

    }
}
